#--
# Copyright (c) 2007 Mathew Abonyi
# Please read LICENSE document for more information.
#++

module Retrospectiva
  module Extension
    module SCMTicketUpdate

      # This extension to the Ticket model translates SVN ticket
      # references into actual updates to the ticket.
      module TicketExtension

        def self.included(base)
          base.send(:include, InstanceMethods)
        end
        
        module InstanceMethods
          
          def update_from_reference(ticket_reference)
            update_attributes_from_reference(ticket_reference)
            update_properties_from_reference(ticket_reference)
          end
          
          def update_attributes_from_reference(ticket_reference)
            ticket_reference.each do |property, value|
              case property
              when :user
                set_if_found :user, self.project.find_in_users_by_login(value)
              when :assigned, :assigned_user
                set_if_found :assigned_user, self.project.find_in_users_by_login(value)
              when :milestone
                set_if_found :milestone, self.project.milestones.find(:first, :conditions => ['LOWER(name) = ?', value.downcase])
              when :status, :priority
                set_if_found property, property.to_s.camelize.constantize.find(:first, :conditions => ['LOWER(name) = ?', value.downcase])
              end
            end
          end
          
          def update_properties_from_reference(ticket_reference)
            property_ids = self.ticket_property_ids.dup
            self.project.ticket_property_types.each do |type|
              if name = ticket_reference[type.class_name.downcase.to_sym]
                # Remove all properties of this type
                property_ids -= type.ticket_properties.collect {| prop| prop.id }
                object = type.ticket_properties.detect { |prop| prop.name.downcase == name.downcase }
                property_ids << object.id if object
              end
            end
            self.ticket_property_ids = property_ids
          end
          
          def set_if_found(attribute, value = nil)
            self.send("#{attribute}=", value) if value && self.respond_to?(attribute)
          end
          
        end
      end
    end
  end
end

Ticket.send(:include, Retrospectiva::Extension::SCMTicketUpdate::TicketExtension)
